import { Injectable,UnauthorizedException } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { PrismaService } from '../../prisma/prisma.service';
import { RedisService } from '../redis/redis.service';
import { JwtService } from '@nestjs/jwt';  // 添加这行导入
import { hashText } from '../utils';
import * as bcrypt from 'bcrypt';
@Injectable()
export class UserService {
  constructor(
    private prisma: PrismaService,
    private jwtService: JwtService,
    private redisService: RedisService
  ) {}
  async create(payload: CreateUserDto) {
    // 先检查用户名是否已存在
    const existingUser = await this.prisma.user.findUnique({
      where: { userName: payload.userName },
    });
  
    if (existingUser) {
      return {
        status: false,
        message: '用户名已存在',
      };
    }
  
    const hashedPassword = await bcrypt.hash(payload.password, 10);
   
    // 生成头像用户名hash化
    const newUser = await this.prisma.user.create({
      data: {
        ...payload,
        password: hashedPassword,
        avatar: `https://api.dicebear.com/7.x/avataaars/svg?seed=${hashedPassword}`
      },
    });
    
    return {
      status: true,
      message: '用户创建成功',
    };
  }

  async login(payload: CreateUserDto) {
    const user = await this.prisma.user.findUnique({
      where: {
        userName: payload.userName
      },
    });
    
    if (!user) {
      return {
        status: false,
        msg:'用户不存在',
        data: null
      };
    }

    const isPasswordValid = await bcrypt.compare(payload.password, user.password);
    
    if (!isPasswordValid) {
      return {
        status: false,
        msg:'密码错误',
        data: null
      };
    }

    // 生成 token
    const token = this.jwtService.sign({ 
      userId: user.id,
      userName: user.userName,
      avatar: user.avatar
    });

    // 将 token 存入 Redis,设置过期时间为 7 天
    await this.redisService.set(
      `token:${user.id}`,
      token,
      60 * 60 * 24 * 7
    );

    return {
      status: true,
      data: {
        token,
        user: {
          id: user.id,
          userName: user.userName,
          avatar: user.avatar
        }
      }
    };
  }
 
  async getUserInfo(user) {
    if(!user) {
      return {
        status: true,
        msg:'用户不存在',
        data: null
      };
    }
    return {
      status: true,
      data: {
        userName: user.userName,
        id: user.userId,
        avatar: user.avatar
      }
    };
  }
}
